import os
import sys
import io
import threading
import tkinter as tk
from tkinter import filedialog
from tkinter.scrolledtext import ScrolledText
import tkinter.messagebox as messagebox

from common import *


class TextRedirector(io.StringIO):
    def __init__(self, widget):
        self.widget = widget
        super().__init__()

    def write(self, msg):
        # 安全地在主线程中更新UI
        self.widget.after(0, lambda: self.widget.config(state='normal'))
        self.widget.after(0, lambda: self.widget.insert(tk.END, msg))
        self.widget.after(0, lambda: self.widget.see(tk.END))
        self.widget.after(0, lambda: self.widget.config(state='disabled'))


def browse_files():
    file_listbox.delete(0, tk.END)
    save_path.delete(0, tk.END)
    file_paths = filedialog.askopenfilenames()
    for file_path in file_paths:
        extension = os.path.splitext(file_path)[1][1:]
        if extension in FORMAT_LIST:
            file_listbox.insert(tk.END, file_path)

    video_list = file_listbox.get(0, tk.END)
    save_dir = os.path.dirname(video_list[0]) + '/'
    save_path.insert(0, save_dir)


def log_print(message):
    log_window.config(state='normal')  # 确保文本框可编辑
    log_window.insert(tk.END, message + '\n')  # 向文本框末尾添加消息并换行
    log_window.see(tk.END)  # 滚动到文本框的底部
    log_window.config(state='disabled')  # 禁止编辑，使文本框只用于显示


def display_in_center(window, window_size=(200,100), window_offset=(0,0)):
    window_width = window_size[0]
    window_height = window_size[1]
    screen_width = window.winfo_screenwidth() + window_offset[0]
    screen_height = window.winfo_screenheight() + window_offset[1]
    x = int((screen_width - window_width) / 2)
    y = int((screen_height - window_height) / 2)
    window.geometry(f'{window_width}x{window_height}+{x}+{y}')
    return window_width, window_height


def show_help():
    help_window = tk.Toplevel()
    help_window.title('帮助')
    help_text = f'''
{TOOL_NAME}

这是一款可以自动生成视频字幕并对视频进行总结的AI工具
支持多种视频格式：{', '.join(FORMAT_LIST)}

作者：Mark Yang
邮箱：ideamark@qq.com
'''
    help_label = tk.Label(help_window, text=help_text)
    help_label.pack(padx=10, pady=10)
    display_in_center(help_window, (400, 180))


def generate_subtitles():
    url = url_path.get()
    save_dir = save_path.get()
    if not save_dir:
        messagebox.showerror("Error", "请指定保存路径")
        return

    def download_audio(url):
        if url:
            title, _, audio = download_bilibili(url)
            audio_dir = os.path.join(save_dir, AUDIO_DIR)
            if not os.path.exists(audio_dir):
                os.makedirs(audio_dir)
            audio_path = os.path.join(audio_dir, title + '.mp3')
            with open(audio_path, 'wb') as fp:
                fp.write(audio)
            print('Save audio complete.')

    def process():
        video_list = file_listbox.get(0, tk.END)
        clean(save_dir)
        download_audio(url)
        video2audio(video_list, save_dir)
        audio2json(save_dir)
        json2srt(save_dir)

    thread = threading.Thread(target=process)
    thread.daemon = True
    thread.start()


def summerize_subtitles():
    save_dir = save_path.get()
    subtitles_dir = os.path.join(save_dir, SUBTITLES_DIR)
    if not save_dir:
        messagebox.showerror("Error", "请先导入视频")
        return
    elif not (os.path.exists(subtitles_dir) and os.path.isdir(subtitles_dir)):
        messagebox.showerror("Error", "请先生成字幕")
        return
    
    thread = threading.Thread(target=summarize, args=(save_dir,))
    thread.daemon = True
    thread.start()


if __name__ == '__main__':
    root = tk.Tk()
    root.title(TOOL_NAME)
    display_in_center(root, (750, 600))

    url_label = tk.Label(root, text='在线视频网址：', anchor='w')
    url_label.pack()
    
    url_path = tk.Entry(root, width=80)
    url_path.pack()

    file_listbox = tk.Listbox(root, width=80)
    file_listbox.pack(pady=(20, 5))

    browse_button = tk.Button(root, text='导入视频', command=browse_files)
    browse_button.pack(pady=(5, 20))

    save_path_label = tk.Label(root, text='保存路径：', anchor='w')
    save_path_label.pack()
    
    save_path = tk.Entry(root, width=80)
    save_path.pack(pady=(5, 20))

    subtitle_button = tk.Button(root, text='生成字幕', command=generate_subtitles)
    subtitle_button.pack()

    summerize_button = tk.Button(root, text='总结视频', command=summerize_subtitles)
    summerize_button.pack()

    help_button = tk.Button(root, text='使用帮助', command=show_help)
    help_button.pack()

    log_window = ScrolledText(root, width=100, height=10, state='disabled')
    log_window.pack(pady=20)

    # 重定向print到log_window
    sys.stdout = TextRedirector(log_window)

    root.mainloop()
